const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 确保目标文件夹存在
const destinationPath = path.resolve(__dirname, '../../public/imgs');
if (!fs.existsSync(destinationPath)) {
    fs.mkdirSync(destinationPath, { recursive: true });
}

// 通过 filename 属性定制
const storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, destinationPath);
    },
    filename: function (req, file, callback) {
        let originalname = file.originalname;
        let lastIndex = originalname.lastIndexOf('.') + 1;
        let suffix = originalname.slice(lastIndex) || file.mimetype.split('/')[1]; // 获取文件格式

        let dt = new Date();
        let yy = dt.getFullYear();
        let mm = dt.getMonth() + 1;
        let dd = dt.getDate();
        mm = mm < 10 ? '0' + mm : mm;
        dd = dd < 10 ? '0' + dd : dd;
        let str = `${yy}${mm}${dd}`;

        // 生成一个随机字符串
        const randomString = Math.random().toString(36).substring(2, 8); // 生成6位随机字符串

        // 使用随机字符串和时间戳生成文件名
        callback(null, file.fieldname + '-' + str + '-' + randomString + '-' + Date.now() + '.' + suffix);
    }
});

// 生成的图片放入指定文件夹下
const upload = multer({ storage: storage });

// 导出处理图片的方法
module.exports = upload;